<?php
/**
 * Created by PhpStorm.
 * User: eddy
 * Date: 2019/9/30
 * Time: 8:54
 */

namespace iBrand\Shop\Backend\Http\Controllers;

use iBrand\Component\Purchase\Models\StockRecord;
use iBrand\Shop\Backend\Service\CommonService;
use iBrand\Shop\Core\Models\O2oGoods;
use iBrand\Shop\Core\Models\O2oGoodsProducts;
use Illuminate\Support\Carbon;
use Validator;
use DB;
use Excel;
use Maatwebsite\Excel\Collections\SheetCollection;
use Encore\Admin\Facades\Admin as LaravelAdmin;
use Encore\Admin\Layout\Content;

class ImportStockController extends Controller
{
    protected $cache;
    protected $importService;

    public function __construct(CommonService $commonService)
    {
        $this->cache = cache();
        $this->importService = $commonService;
    }


    public function index()
    {
        $this->cache->forget('stockImportCount');
        return LaravelAdmin::content(function (Content $content) {

            $content->header('库存导入');

            $content->breadcrumb(
                ['text' => '采购单', 'url' => 'store/attribute', 'no-pjax' => 1],
                ['text' => '库存导入', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '采购单']

            );
            $content->body(view('shop-backend::importStock.index'));
        });
    }

    public function importStockModal()
    {
        $calculateUrl = route('admin.shop.importStock.getImportDataCount') . '?path=' . request('path');

        return view('shop-backend::importStock.import_modal', compact('calculateUrl'));
    }

    /**
     * 计算导入的数据数量
     * @param $path
     */
    public function getImportDataCount()
    {
        $filename = 'public' . request('path');

        Excel::load($filename, function ($reader) {
            $reader = $reader->getSheet(0);
            //获取表中的数据
            $count = count($reader->toArray()) - 1;
            $expiresAt = Carbon::now()->addMinutes(60);
            $this->cache->forget('stockImportCount');
            $this->cache->put('stockImportCount', $count, $expiresAt);
        });

        $limit = 10;
        $total = ceil($this->cache->get('stockImportCount') / $limit);

        $url = route('admin.shop.importStock.saveImportData', ['total' => $total, 'limit' => $limit, 'path' => request('path')]);
        return $this->ajaxJson(true, ['status' => 'goon', 'url' => $url]);
    }

    /**
     * 执行导入操作
     * @return mixed
     */
    public function saveImportData()
    {
        $filename = 'public' . request('path');
        $conditions = [];
        $page = request('page') ? request('page') : 1;
        $total = request('total');
        $limit = request('limit');

        if ($page > $total) {
            return $this->ajaxJson(true, ['status' => 'complete']);
        }

        Excel::load($filename, function ($reader) use ($conditions, $page, $limit) {
            $reader = $reader->get();
            if ($reader instanceof SheetCollection) {
                $reader = $reader->first();
            }
            $data = $reader->forPage($page, $limit)->toArray();

            if (count($data) > 0) {
                $this->importService->importStock(session('shop_id'), $data);
            }
        });

        $url = route('admin.shop.importStock.saveImportData', ['page' => $page + 1, 'total' => $total, 'limit' => $limit, 'path' => request('path')]);
        return $this->ajaxJson(true, ['status' => 'goon', 'url' => $url, 'current_page' => $page, 'total' => $total]);
    }

    public function fixStoreNum()
    {
        $page = request('page') ? request('page') + 1 : 2;
        $limit = request('limit') ? request('limit') : 15;
        $message = '';
        $shop_id = session('shop_id');

        $products = O2oGoodsProducts::where('shop_id', $shop_id)->paginate($limit);

        if ($products->count()) {
            foreach ($products as $item) {
                $records = StockRecord::where('shop_id', $shop_id)->where('item_id', $item->product_id)->get();

                $p_num = 0;
                if ($records->count() > 0) {
                    $p_num = $records->sum('change_count');
                }
                $item->store_nums = $p_num;
                $item->save();

                $goods = O2oGoods::find($item->o2o_goods_id);
                $gps = O2oGoodsProducts::where('o2o_goods_id', $item->o2o_goods_id)->get();
                $g_num = 0;
                if ($gps->count()) {
                    $g_num = $gps->sum('store_nums');
                }
                $goods->store_nums = $g_num;
                $goods->save();
            }

        } else {
            $message = '全部处理完成';
        }

        $interval = 5;
        $url_bit = route('admin.shop.goods.fixStoreNum', ['page' => $page, 'limit' => $limit]);

        return view('shop-backend::show_message', compact('message', 'interval', 'url_bit'));
    }
}